package com.hy.hash;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Intersection {


    static int [] intersection(Integer [] nums1,Integer [] nums2){
        if ((nums1 == null && nums1.length == 0) || (nums2 == null && nums2.length == 0)){
            return new int[0];
        }
        Set<Integer> set1 = new HashSet<>();
        Set<Integer> resSet = new HashSet<>();

        //遍历数组1
        for (int i : nums1) {
            set1.add(i);
        }

        //遍历数组2的过程中判断哈希表中是否存在该元素
        for (int i : nums2) {
            if (set1.contains(i)){
                resSet.add(i);
            }
        }
        int[] s = new int[resSet.size()];
        int index = 0;
        for (Integer integer : resSet) {
            s[index] = integer;
            index++;
        }
        return s;
    }

    /**
     * 利用 集合 取交集
     * @param nums1
     * @param nums2
     * @return
     */
    static  List<Integer> intersection2(Integer [] nums1,Integer [] nums2){
        // 交集
        List<Integer> n1 = Arrays.asList(nums1);
        List<Integer> n2 = Arrays.asList(nums2);
        List<Integer> res = n1.stream().distinct().filter(x -> n2.contains(x)).collect(Collectors.toList());

        // 并集
        List<Integer> l1 = n1.parallelStream().collect(Collectors.toList());
        List<Integer> l2 = n2.parallelStream().collect(Collectors.toList());
        l1.addAll(l2);
        System.out.println("并集： "+l1.toString());
        System.out.println("去重并集： "+l1.stream().distinct().collect(Collectors.toList()).toString());
        // 差集
        List<Integer> ss = l1.stream().filter(x -> !l2.contains(x)).collect(Collectors.toList());
        System.out.println("差集："+ss.toString());

        return res;
    }
    public static void main(String[] args) {
        Integer [] x1 = {1,2,3,2,1,9,7};
        Integer [] x2 = {1,3,0,12,11,90,7};
        int[] intersection = intersection(x1, x2);
        for (int i : intersection) {
            System.out.println("intersection data: "+ i);
        }
        List<Integer> integers = intersection2(x1, x2);
        System.out.println("intersection data: "+integers.toString());


    }
}
